<template>
  <div class="app-container">
    <el-container>
      <el-main>
        <!-- 搜索和操作栏 -->
        <div class="top">
          <el-row>
            <el-col :span="16">
              <el-input
                v-model="listQuery.kw"
                placeholder="搜索聊天机器人名称"
                style="width: 350px"
                @keyup.enter.native="searchChatBots"
              >
                <el-button slot="append" icon="el-icon-search" @click="searchChatBots" />
              </el-input>
            </el-col>
            <el-col :span="8" class="text-right">
              <el-button
                v-if="hasUserPermission"
                class="add-btn"
                type="primary"
                @click="showChatBotDialog"
              >
                新建聊天机器人
              </el-button>
            </el-col>
          </el-row>
        </div>

        <!-- 聊天机器人列表 -->
        <el-table
          v-loading="listLoading"
          :data="chatBotList"
          border
          style="width: 100%"
        >
          <el-table-column prop="name" label="机器人名称" min-width="150">
            <template slot-scope="scope">
              <el-link type="primary" @click="viewChatBotDetail(scope.row)">
                {{ scope.row.name }}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column prop="waha_session_name" label="WAHA会话" width="120" />
          <el-table-column prop="vector_knowledge_base_name" label="知识库" width="120" />
          <el-table-column prop="for_all_chat" label="作用范围" width="120">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.for_all_chat" type="success" size="small">
                全部对话
              </el-tag>
              <el-tag v-else type="info" size="small">
                {{ (scope.row.chat_ids && scope.row.chat_ids.length) || 0 }}个指定对话
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="default_model" label="默认模型" width="120" />
          <el-table-column prop="default_temperature" label="温度" width="80">
            <template slot-scope="scope">
              {{ scope.row.default_temperature }}
            </template>
          </el-table-column>
          <el-table-column prop="default_max_tokens" label="最大Token" width="100">
            <template slot-scope="scope">
              {{ scope.row.default_max_tokens | formatTokens }}
            </template>
          </el-table-column>
          <el-table-column prop="create_at" label="创建时间" width="150">
            <template slot-scope="scope">
              {{ formatDate(scope.row.create_at) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280" fixed="right">
            <template slot-scope="scope">
              <el-button
                v-if="!scope.row.for_all_chat"
                size="mini"
                type="info"
                @click="showChatDrawer(scope.row)"
              >
                关联对话
              </el-button>
              <el-button
                v-if="hasUserPermission"
                size="mini"
                @click="editChatBot(scope.row)"
              >
                编辑
              </el-button>
              <el-button
                v-if="hasUserPermission"
                size="mini"
                type="danger"
                @click="deleteChatBot(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
          v-show="total > 0"
          background
          :current-page="listQuery.page"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="listQuery.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          class="mt-pagination"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </el-main>
    </el-container>

    <!-- 新建/编辑聊天机器人对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="800px"
      @close="resetForm"
    >
      <el-form
        ref="chatBotForm"
        :model="chatBotForm"
        :rules="chatBotRules"
        label-width="120px"
      >
        <el-form-item label="机器人名称" prop="name">
          <el-input v-model="chatBotForm.name" placeholder="请输入聊天机器人名称" />
        </el-form-item>

        <el-form-item label="关联会话" prop="waha_session_id">
          <el-select v-model="chatBotForm.waha_session_id" placeholder="请选择WAHA会话" style="width: 100%;">
            <el-option
              v-for="session in wahaSessionList"
              :key="session.id"
              :label="session.session_name + ' (' + session.phone + ')'"
              :value="session.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="关联知识库" prop="vector_knowledge_base_id">
          <el-select v-model="chatBotForm.vector_knowledge_base_id" placeholder="请选择向量知识库" style="width: 100%;">
            <el-option
              v-for="kb in knowledgeBaseList"
              :key="kb.id"
              :label="kb.name"
              :value="kb.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="作用范围">
          <el-radio-group v-model="chatBotForm.for_all_chat">
            <el-radio :label="true">应用于该会话的所有对话</el-radio>
            <el-radio :label="false">仅应用于指定的对话</el-radio>
          </el-radio-group>
          <div class="form-tip">
            选择"所有对话"时，机器人将处理该WAHA会话中的所有消息；选择"指定对话"时，需要手动添加对话ID
          </div>
        </el-form-item>

        <el-form-item label="系统提示词">
          <el-input
            v-model="chatBotForm.system_prompt"
            type="textarea"
            :rows="4"
            placeholder="请输入系统提示词，用于定义聊天机器人的角色和行为"
          />
        </el-form-item>

        <el-divider content-position="left">AI模型配置</el-divider>

        <el-form-item label="默认模型" prop="default_model">
          <el-select v-model="chatBotForm.default_model" placeholder="请选择默认AI模型" style="width: 100%;">
            <el-option-group label="OpenAI模型">
              <el-option label="GPT-4.1" value="gpt-4.1" />
              <el-option label="GPT-4" value="gpt-4" />
              <el-option label="GPT-4 Turbo" value="gpt-4-turbo" />
              <el-option label="GPT-3.5 Turbo" value="gpt-3.5-turbo" />
            </el-option-group>
            <el-option-group label="其他模型">
              <el-option label="Claude-3" value="claude-3" />
              <el-option label="Gemini" value="gemini" />
            </el-option-group>
          </el-select>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="温度参数">
              <el-slider
                v-model="chatBotForm.default_temperature"
                :min="0"
                :max="2"
                :step="0.1"
                show-input
                :input-size="'small'"
              />
              <span class="form-tip">控制输出的随机性，0为确定性，2为最随机</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="Top P">
              <el-slider
                v-model="chatBotForm.default_top_p"
                :min="0"
                :max="1"
                :step="0.1"
                show-input
                :input-size="'small'"
              />
              <span class="form-tip">核采样参数，控制候选词范围</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="最大Token数">
          <el-input-number
            v-model="chatBotForm.default_max_tokens"
            :min="1"
            :max="100000000"
            :step="1000"
            style="width: 200px"
          />
          <span class="form-tip" style="margin-left: 10px">限制单次对话的最大令牌数</span>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="频率惩罚">
              <el-slider
                v-model="chatBotForm.default_frequency_penalty"
                :min="-2"
                :max="2"
                :step="0.1"
                show-input
                :input-size="'small'"
              />
              <span class="form-tip">减少重复词汇的出现频率</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="存在惩罚">
              <el-slider
                v-model="chatBotForm.default_presence_penalty"
                :min="-2"
                :max="2"
                :step="0.1"
                show-input
                :input-size="'small'"
              />
              <span class="form-tip">增加讨论新话题的可能性</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>

    <!-- 关联对话抽屉 -->
    <el-drawer
      v-if="!currentChatBot.for_all_chat"
      :title="`${currentChatBot.name} - 关联对话管理`"
      :visible.sync="chatDrawerVisible"
      direction="rtl"
      size="60%"
      :before-close="handleChatDrawerClose"
    >
      <div class="drawer-content">
        <!-- 添加新对话 -->
        <div class="add-chat-section">
          <el-row :gutter="10" type="flex" align="middle">
            <el-col :span="16">
              <el-input
                v-model="newChatId"
                placeholder="请输入对话ID (如: 1234567890@c.us 或 group123@g.us)"
                @keyup.enter.native="addChatId"
              >
                <template slot="prepend">新增对话ID</template>
              </el-input>
            </el-col>
            <el-col :span="8">
              <el-button
                type="primary"
                :loading="addChatLoading"
                :disabled="!newChatId.trim()"
                @click="addChatId"
              >
                添加
              </el-button>
            </el-col>
          </el-row>
          <div class="form-tip">
            支持格式：用户对话（xxx@c.us）或群组对话（xxx@g.us）
          </div>
        </div>

        <!-- 关联对话列表 -->
        <div class="chat-list-section">
          <div class="section-title">
            <h4>已关联对话列表 ({{ chatList.length }})</h4>
            <el-button
              size="small"
              :loading="chatListLoading"
              icon="el-icon-refresh"
              @click="fetchChatList"
            >
              刷新
            </el-button>
          </div>

          <el-table
            v-loading="chatListLoading"
            :data="chatList"
            border
            style="width: 100%"
            max-height="400"
          >
            <el-table-column prop="chat_id" label="对话ID" min-width="200">
              <template slot-scope="scope">
                <el-tag
                  :type="scope.row.chat_id.endsWith('@g.us') ? 'success' : 'primary'"
                  size="small"
                >
                  {{ scope.row.chat_id.endsWith('@g.us') ? '群组' : '用户' }}
                </el-tag>
                <span style="margin-left: 8px">{{ scope.row.chat_id }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="create_at" label="关联时间" width="150">
              <template slot-scope="scope">
                {{ formatDate(scope.row.create_at) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="danger"
                  :loading="scope.row.deleting"
                  @click="deleteChatId(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div v-if="chatList.length === 0 && !chatListLoading" class="empty-state">
            <i class="el-icon-chat-dot-round" style="font-size: 48px; color: #ddd;" />
            <p>暂无关联对话</p>
            <p class="empty-tip">添加对话ID后，该聊天机器人将能处理对应的对话消息</p>
          </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import {
  getChatBotList,
  createChatBot,
  updateChatBot,
  deleteChatBot
} from '@/api/chatbot/chatbot'
import { getWahaSessionList } from '@/api/chatbot/waha-session'
import { getVectorKnowledgeBaseList } from '@/api/chatbot/knowledge-base'
import {
  getChatBotChatList,
  createChatBotChat,
  deleteChatBotChat
} from '@/api/chatbot/chatbot-chat'

export default {
  name: 'ChatBotConfig',
  filters: {
    formatTokens(value) {
      if (!value) return '0'
      if (value >= 1000000) {
        return (value / 1000000).toFixed(1) + 'M'
      } else if (value >= 1000) {
        return (value / 1000).toFixed(1) + 'K'
      }
      return value.toString()
    }
  },
  data() {
    return {
      // 列表相关
      chatBotList: [],
      listLoading: false,
      total: 0,
      listQuery: {
        page: 1,
        pageSize: 20,
        kw: ''
      },

      // 对话框相关
      dialogVisible: false,
      dialogTitle: '新建聊天机器人',
      submitLoading: false,
      isEdit: false,
      currentChatBotId: null,

      // 表单相关
      chatBotForm: {
        name: '',
        waha_session_id: null,
        vector_knowledge_base_id: null,
        for_all_chat: false,
        system_prompt: '',
        default_model: 'gpt-4.1',
        default_temperature: 0.7,
        default_top_p: 1,
        default_max_tokens: 100000000,
        default_frequency_penalty: 0,
        default_presence_penalty: 0
      },
      chatBotRules: {
        name: [
          { required: true, message: '请输入聊天机器人名称', trigger: 'blur' }
        ],
        waha_session_id: [
          { required: true, message: '请选择WAHA会话', trigger: 'change' }
        ],
        vector_knowledge_base_id: [
          { required: true, message: '请选择向量知识库', trigger: 'change' }
        ],
        default_model: [
          { required: true, message: '请选择默认模型', trigger: 'change' }
        ]
      },

      // 下拉列表数据
      wahaSessionList: [],
      knowledgeBaseList: [],

      // 关联对话抽屉相关
      chatDrawerVisible: false,
      currentChatBot: {},
      chatList: [],
      chatListLoading: false,
      newChatId: '',
      addChatLoading: false
    }
  },
  computed: {
    hasUserPermission() {
      return this.$store.getters.roles.indexOf('chatbot_user') !== -1 ||
             this.$store.getters.roles.indexOf('admin') !== -1
    }
  },
  created() {
    this.fetchChatBotList()
    this.fetchWahaSessionList()
    this.fetchKnowledgeBaseList()
  },
  methods: {
    // 获取聊天机器人列表
    fetchChatBotList() {
      this.listLoading = true
      const params = new URLSearchParams()
      params.append('page', this.listQuery.page)
      params.append('pagesize', this.listQuery.pageSize)
      if (this.listQuery.kw) params.append('kw', this.listQuery.kw)

      getChatBotList(params.toString())
        .then(response => {
          if (response.success) {
            this.chatBotList = response.data.data || []
            this.total = response.data.total || 0
          } else {
            this.$message.error(response.msg || '获取聊天机器人列表失败')
          }
        })
        .catch(error => {
          console.error('获取聊天机器人列表失败:', error)
          this.$message.error('获取聊天机器人列表失败')
        })
        .finally(() => {
          this.listLoading = false
        })
    },

    // 获取WAHA会话列表
    fetchWahaSessionList() {
      getWahaSessionList('')
        .then(response => {
          if (response.success) {
            this.wahaSessionList = response.data.data || []
          }
        })
        .catch(error => {
          console.error('获取WAHA会话列表失败:', error)
        })
    },

    // 获取知识库列表
    fetchKnowledgeBaseList() {
      getVectorKnowledgeBaseList('')
        .then(response => {
          if (response.success) {
            this.knowledgeBaseList = response.data.data || []
          }
        })
        .catch(error => {
          console.error('获取知识库列表失败:', error)
        })
    },

    // 搜索聊天机器人
    searchChatBots() {
      this.listQuery.page = 1
      this.fetchChatBotList()
    },

    // 分页处理
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.fetchChatBotList()
    },

    handlePageChange(val) {
      this.listQuery.page = val
      this.fetchChatBotList()
    },

    // 显示聊天机器人对话框
    showChatBotDialog() {
      this.dialogTitle = '新建聊天机器人'
      this.isEdit = false
      this.currentChatBotId = null
      this.dialogVisible = true
    },

    // 编辑聊天机器人
    editChatBot(chatbot) {
      this.dialogTitle = '编辑聊天机器人'
      this.isEdit = true
      this.currentChatBotId = chatbot.id
      this.chatBotForm = {
        name: chatbot.name,
        waha_session_id: chatbot.waha_session_id,
        vector_knowledge_base_id: chatbot.vector_knowledge_base_id,
        for_all_chat: chatbot.for_all_chat || false,
        system_prompt: chatbot.system_prompt || '',
        default_model: chatbot.default_model || 'gpt-4.1',
        default_temperature: chatbot.default_temperature || 0.7,
        default_top_p: chatbot.default_top_p || 1,
        default_max_tokens: chatbot.default_max_tokens || 100000000,
        default_frequency_penalty: chatbot.default_frequency_penalty || 0,
        default_presence_penalty: chatbot.default_presence_penalty || 0
      }
      this.dialogVisible = true
    },

    // 查看聊天机器人详情
    viewChatBotDetail(chatbot) {
      this.$message.info(`查看聊天机器人详情: ${chatbot.name}`)
      // 这里可以实现查看详情的逻辑
    },

    // 删除聊天机器人
    deleteChatBot(chatbot) {
      this.$confirm(`确定要删除聊天机器人 "${chatbot.name}" 吗？此操作不可恢复！`, '删除聊天机器人', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteChatBot(chatbot.id)
          .then(response => {
            if (response.success) {
              this.$message.success('删除聊天机器人成功')
              this.fetchChatBotList()
            } else {
              this.$message.error(response.msg || '删除聊天机器人失败')
            }
          })
          .catch(error => {
            console.error('删除聊天机器人失败:', error)
            this.$message.error('删除聊天机器人失败')
          })
      })
    },

    // 提交表单
    submitForm() {
      this.$refs.chatBotForm.validate((valid) => {
        if (valid) {
          this.submitLoading = true

          const action = this.isEdit
            ? updateChatBot(this.currentChatBotId, this.chatBotForm)
            : createChatBot(this.chatBotForm)

          action
            .then(response => {
              if (response.success) {
                this.$message.success(this.isEdit ? '更新聊天机器人成功' : '创建聊天机器人成功')
                this.dialogVisible = false
                this.fetchChatBotList()
              } else {
                this.$message.error(response.msg || (this.isEdit ? '更新聊天机器人失败' : '创建聊天机器人失败'))
              }
            })
            .catch(error => {
              console.error(this.isEdit ? '更新聊天机器人失败:' : '创建聊天机器人失败:', error)
              this.$message.error(this.isEdit ? '更新聊天机器人失败' : '创建聊天机器人失败')
            })
            .finally(() => {
              this.submitLoading = false
            })
        }
      })
    },

    // 重置表单
    resetForm() {
      this.chatBotForm = {
        name: '',
        waha_session_id: null,
        vector_knowledge_base_id: null,
        for_all_chat: false,
        system_prompt: '',
        default_model: 'gpt-4.1',
        default_temperature: 0.7,
        default_top_p: 1,
        default_max_tokens: 100000000,
        default_frequency_penalty: 0,
        default_presence_penalty: 0
      }
      if (this.$refs.chatBotForm) {
        this.$refs.chatBotForm.resetFields()
      }
    },

    // 显示关联对话抽屉
    showChatDrawer(chatbot) {
      this.currentChatBot = chatbot
      this.chatDrawerVisible = true
      this.fetchChatList()
    },

    // 关闭关联对话抽屉
    handleChatDrawerClose(done) {
      this.newChatId = ''
      this.chatList = []
      done()
    },

    // 获取关联对话列表
    fetchChatList() {
      if (!this.currentChatBot.id) return

      this.chatListLoading = true
      const params = new URLSearchParams()
      params.append('chatbot_id', this.currentChatBot.id)
      params.append('pagesize', 1000)

      getChatBotChatList(params.toString())
        .then(response => {
          if (response.success) {
            this.chatList = response.data.data || []
          } else {
            this.$message.error(response.msg || '获取对话列表失败')
          }
        })
        .catch(error => {
          console.error('获取对话列表失败:', error)
          this.$message.error('获取对话列表失败')
        })
        .finally(() => {
          this.chatListLoading = false
        })
    },

    // 添加新的对话ID
    addChatId() {
      if (!this.newChatId.trim()) {
        this.$message.warning('请输入对话ID')
        return
      }

      // 验证对话ID格式
      const chatIdPattern = /^.+@[cg]\.us$/
      if (!chatIdPattern.test(this.newChatId.trim())) {
        this.$message.error('对话ID格式不正确，应为 xxx@c.us 或 xxx@g.us 格式')
        return
      }

      this.addChatLoading = true

      const data = {
        chatbot_id: this.currentChatBot.id,
        chat_id: this.newChatId.trim()
      }

      createChatBotChat(data)
        .then(response => {
          if (response.success) {
            this.$message.success('添加对话ID成功')
            this.newChatId = ''
            this.fetchChatList()
          } else {
            this.$message.error(response.msg || '添加对话ID失败')
          }
        })
        .catch(error => {
          console.error('添加对话ID失败:', error)
          this.$message.error('添加对话ID失败')
        })
        .finally(() => {
          this.addChatLoading = false
        })
    },

    // 删除对话ID
    deleteChatId(chat) {
      this.$confirm(`确定要删除对话ID "${chat.chat_id}" 吗？`, '删除对话', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$set(chat, 'deleting', true)

        deleteChatBotChat(chat.id)
          .then(response => {
            if (response.success) {
              this.$message.success('删除对话ID成功')
              this.fetchChatList()
            } else {
              this.$message.error(response.msg || '删除对话ID失败')
            }
          })
          .catch(error => {
            console.error('删除对话ID失败:', error)
            this.$message.error('删除对话ID失败')
          })
          .finally(() => {
            this.$set(chat, 'deleting', false)
          })
      })
    },

    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '-'
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN')
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.top {
  margin-bottom: 20px;
}

.add-btn {
  float: right;
}

.text-right {
  text-align: right;
}

.mt-pagination {
  margin-top: 20px;
  text-align: center;
}

.dialog-footer {
  text-align: right;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  display: block;
  margin-top: 4px;
}

.el-divider {
  margin: 20px 0;
}

.el-slider {
  margin-bottom: 10px;
}

/* 抽屉样式 */
.drawer-content {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.add-chat-section {
  margin-bottom: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.chat-list-section {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.section-title h4 {
  margin: 0;
  color: #333;
  font-size: 16px;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #999;
}

.empty-state p {
  margin: 10px 0;
}

.empty-tip {
  font-size: 12px;
  color: #ccc;
}

.el-tag {
  margin-right: 8px;
}
</style>
